//
//  MoodChangeTableViewCell.swift
//  MoodDiary
//
//  Created by OVIX on 2020/12/11.
//

import UIKit
import Charts

protocol MoodChangeTableViewCellDelegate: NSObjectProtocol {
    func moodChangeTableViewCellShare()
}

class MoodChangeTableViewCell: UITableViewCell {
    
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var label: UILabel!
    
    var chartSwiftView: ChartSwiftView?
    var chartSwiftView2: ChartSwiftView2?
    
    var isMonth: Bool?
    
    var delegate: MoodChangeTableViewCellDelegate?
    
    var currentYear: Int?
    var currentMonth: Int?
    
    private var lineChartView = LineChartView()
    
    var weekChangeDic: [String: [String]]? {
        didSet {
            
            guard let weekDic = weekChangeDic else {
                return
            }
            print("weekDic === \(weekDic)")
            var maxMoodCount = 0
            var yValue: [ChartDataEntry] = []
            for i in 0...6 {
                var moodCount = 0
                let weekString = getWeekString(i)
                weekDic.forEach { (key, value) in
                    value.forEach { timeStamp in
                        let dayWeek = NSString.dateWeek(withTimeStamp: timeStamp)
                        if dayWeek == weekString {
                            moodCount += 1
                        }
                    }
                }
                if moodCount > maxMoodCount {
                    maxMoodCount = moodCount
                }
                let entry = ChartDataEntry(x: Double(i), y: Double(moodCount))
                yValue.append(entry)
            }

            let yAxis = lineChartView.leftAxis
            yAxis.axisMaximum = Double(maxMoodCount + 3)


            let xAxis = lineChartView.xAxis
            xAxis.labelPosition = .bottom
            xAxis.labelTextColor = .black
            xAxis.axisLineColor = .black.withAlphaComponent(0.5)
            let xValues = ["周一","周二","周三","周四","周五","周六", "周日"]
            lineChartView.xAxis.granularity = 1
            lineChartView.xAxis.axisMinimum = 0
            lineChartView.xAxis.axisMaximum = 6
            lineChartView.xAxis.forceLabelsEnabled = true
            lineChartView.xAxis.granularityEnabled = true
            lineChartView.xAxis.labelCount = 7
            lineChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xValues)

            setData(yValue)
            
            
        }
    }
    
    private func getWeekString(_ index: Int) -> String {
        var indexStr = ""
        switch index {
        case 0:
            indexStr = "星期一"
        case 1:
            indexStr = "星期二"
        case 2:
            indexStr = "星期三"
        case 3:
            indexStr = "星期四"
        case 4:
            indexStr = "星期五"
        case 5:
            indexStr = "星期六"
        case 6:
            indexStr = "星期日"
        default:
            break
        }
        return indexStr
    }
    
    var monthChangeDic: [String: [String]]? {
        didSet {
            
            guard let monthDic = monthChangeDic else {
                return
            }
            var monthDays = 0
            
            if currentYear == nil {
                currentYear = Int(NSString.currentYear()) ?? 0
            }
            if currentMonth == nil {
                currentMonth = Int(NSString.currentMonth()) ?? 0
            }
            
            guard let currentYear = currentYear else { return }
            guard let currentMonth = currentMonth else { return }
            
            switch currentMonth {
            case 1, 3, 5, 7, 8, 10, 12: monthDays = 31
            case 2:
                if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) { monthDays = 29 } else { monthDays = 28 }
            default: monthDays = 30
            }
            
            var maxMoodCount = 0
            var yValue: [ChartDataEntry] = []
            for i in 1...monthDays {
                var moodCount = 0
                monthDic.forEach { (key, value) in
                    value.forEach { timeStamp in
                        let dayMonth = NSString.getDay(timeStamp)
                        if dayMonth == String.init(format: "%02d", i) {
                            moodCount += 1
                        }
                    }
                }
                if moodCount > maxMoodCount {
                    maxMoodCount = moodCount
                }
                let entry = ChartDataEntry(x: Double(i), y: Double(moodCount))
                yValue.append(entry)
            }


            let yAxis = lineChartView.leftAxis
            yAxis.axisMaximum = Double(maxMoodCount + 3)


            let xAxis = lineChartView.xAxis
            xAxis.labelPosition = .bottom
            xAxis.labelTextColor = .black
            xAxis.axisLineColor = .black.withAlphaComponent(0.5)

            var xValues: [String] = []
            for i in 1...monthDays {
                xValues.append("\(i)")
            }
            
            lineChartView.xAxis.setLabelCount(monthDays/3, force: false)
            lineChartView.xAxis.granularity = 2
            lineChartView.xAxis.axisMinimum = 1
            lineChartView.xAxis.axisMaximum = Double(monthDays)
            lineChartView.xAxis.granularityEnabled = true
            lineChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xValues)

            setData(yValue)
            
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }
    
    var beginEndDay = "" {
        didSet {
            
            if isMonth == false {
                let str = "情绪变化 " + beginEndDay
                let attStr = NSMutableAttributedString(string: str)
                attStr.addAttributes([.font: UIFont.systemFont(ofSize: 14.0, weight: .light), .foregroundColor: UIColor.hexColor(hex: "#D4D4D4")], range: NSMakeRange(5, beginEndDay.count))
                label.attributedText = attStr
                return
            }
            
            let str = "情绪变化 " + (beginEndDay as NSString).substring(to: 2) + "月"
            let attStr = NSMutableAttributedString(string: str)
            attStr.addAttributes([.font: UIFont.systemFont(ofSize: 14.0, weight: .light), .foregroundColor: UIColor.hexColor(hex: "#D4D4D4")], range: NSMakeRange(5, 2 + 1))
            label.attributedText = attStr
            
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        bgView.layer.cornerRadius = 12.0
        bgView.layer.shadowOpacity = 1.0
        bgView.layer.shadowOffset = CGSize(width: 0, height: 0)
        bgView.layer.shadowRadius = 2.0
        bgView.layer.shadowColor = UIColor.init(white: 0.6, alpha: 0.4).cgColor
        
        lineChartView.frame = CGRect(x: 10.0, y: 40.0, width: screen_width - 30.0 * 2 - 10.0, height: 300.0 - 3.0 - 40.0 - 5.0 - 15.0)
        lineChartView.backgroundColor = .white
        lineChartView.rightAxis.enabled = false
        lineChartView.scaleXEnabled = false
        lineChartView.scaleYEnabled = false
        lineChartView.legend.enabled = false

        let yAxis = lineChartView.leftAxis
        yAxis.labelTextColor = .black
        yAxis.axisLineColor = .black.withAlphaComponent(0.5)
        yAxis.granularity = 1
        yAxis.granularityEnabled = true

        bgView.addSubview(lineChartView)
    }
    
    func setData(_ yValue: [ChartDataEntry]) {
        let set1 = LineChartDataSet(entries: yValue, label: "")
        set1.mode = .cubicBezier
        set1.drawCirclesEnabled = false
        
        set1.lineWidth = 1
        let yellow = UIColor(red: 241/255, green: 220/255, blue: 166/255, alpha: 1)
        set1.setColor(yellow)
        let color2 = UIColor.clear.cgColor
        let gradientColors = [UIColor.yellow.cgColor, color2] as CFArray
        let colorLocations:[CGFloat] = [0.5, 0.0]
        let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations)
        set1.fill = Fill.fillWithLinearGradient(gradient!, angle: 90.0)
        set1.drawFilledEnabled = true
        
        let data = LineChartData(dataSet: set1)
        data.setDrawValues(false)
        lineChartView.data = data
    }
    
    @IBAction func action(_ sender: Any) {
        delegate?.moodChangeTableViewCellShare()
    }
    
}
